package com.activities;

import java.util.ArrayList;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.Utility.MessageManager;
import com.Utility.Utility;
import com.Utility.WebServiceCommunicator.WebServiceFlag;
import com.adapters.GroupMemberAdapter;
import com.adapters.db.ContactTableAdapter;
import com.adapters.db.GroupMemberTableAdapter;
import com.controls.ws.ContactWSControl;
import com.controls.ws.GroupWSControl;
import com.dialogs.DeleteConfirmDialog;
import com.dialogs.LoadingDialog;
import com.events.WebServiceCommunicatorListener;
import com.objects.Contact;
import com.objects.Group;
import com.objects.GroupMember;
import com.senditcertified.mail.R;
import com.views.NoScrollListView;

public class EditGroupActivity extends BaseActivity implements OnClickListener,
		WebServiceCommunicatorListener {
	public static final String KEY_GROUP_ITEM = "group_item";
	private EditText mEdtGroupName;
	private TextView mTvGroupMemberNodata;
	private Spinner mSpContact;
	private NoScrollListView mLvContact;

	private LoadingDialog mDialog;
	private GroupWSControl mWSGroup;
	private ContactWSControl mWSContact;
	private ContactTableAdapter mTAContact;
	private GroupMemberTableAdapter mTAGroupMember;
	private ArrayList<Contact> lstContact;
	private GroupMemberAdapter mGroupMemberAdapter;
	private DeleteConfirmDialog mDeleteConfirmDialog;
	private Group group;

	@Override
	protected int initLayout() {
		return R.layout.activity_edit_group;
	}

	@Override
	protected void initViews() {
		mEdtGroupName = (EditText) findViewById(R.id.edt_group_name);
		mSpContact = (Spinner) findViewById(R.id.spn_contact);
		mTvGroupMemberNodata = (TextView) findViewById(R.id.tv_nodata);
		mLvContact = (NoScrollListView) findViewById(R.id.list);
	}

	@Override
	protected void initComponents() {
		group = getIntent().getParcelableExtra(KEY_GROUP_ITEM);
		if (group == null)
			finish();
		else {
			mSpContact.setPrompt("[Choose from Contacts]");
			mEdtGroupName.setText(group.getTitle());
			mTAContact = new ContactTableAdapter(this);
			mTAGroupMember = new GroupMemberTableAdapter(this);
			// contact
			lstContact = mTAContact.getItems();
			if (lstContact != null && lstContact.size() > 0) {
				Contact contact = new Contact();
				contact.setName("[Choose from Contacts]");
				lstContact.add(0, contact);
				ArrayAdapter<Contact> contactAdapter = new ArrayAdapter<Contact>(
						this, R.layout.spinner_item, lstContact);
				contactAdapter.setDropDownViewResource(R.layout.spinner_item);
				mSpContact.setAdapter(contactAdapter);

			}
			if (mWSContact == null)
				mWSContact = new ContactWSControl(this, this);
			mWSContact.getContacts(Utility.getStringPreference(this,
					Utility.KEY_LOGIN_TOKEN, ""));
			if (mWSGroup == null)
				mWSGroup = new GroupWSControl(this, this);
			mWSGroup.getGroupName(Utility.getStringPreference(this,
					Utility.KEY_LOGIN_TOKEN, ""), group.getID());

		}

	}

	private void setGroupMemberAdapter(ArrayList<GroupMember> lstItem) {
		if (lstItem != null && lstItem.size() > 0) {
			mGroupMemberAdapter = new GroupMemberAdapter(this, lstItem) {
				@Override
				public void onViewEdit(final int pos) {
					if (mDeleteConfirmDialog != null) {
						mDeleteConfirmDialog.dismiss();
						mDeleteConfirmDialog = null;
					}
					mDeleteConfirmDialog = new DeleteConfirmDialog(getParent()) {
						@Override
						public void onConfirm() {
							if (mWSGroup == null)
								mWSGroup = new GroupWSControl(
										EditGroupActivity.this,
										EditGroupActivity.this);
							mWSGroup.removeGroupMember(Utility
									.getStringPreference(
											EditGroupActivity.this,
											Utility.KEY_LOGIN_TOKEN, ""),
									mGroupMemberAdapter.getItem(pos).getID()
											+ "");
						}
					};
					mDeleteConfirmDialog.setTitle("Remove Contact Member");
					mDeleteConfirmDialog
							.setMessage("Are you sure you wish to remove this member from group?");
					mDeleteConfirmDialog.show();

				}
			};
			mTvGroupMemberNodata.setVisibility(View.GONE);
			mLvContact.setVisibility(View.VISIBLE);
			mLvContact.setAdapter(mGroupMemberAdapter);
		} else {
			mTvGroupMemberNodata.setVisibility(View.VISIBLE);
			mLvContact.setVisibility(View.GONE);
			mGroupMemberAdapter = null;
		}
	}

	@Override
	protected void addListener() {
		findViewById(R.id.ln_save_group).setOnClickListener(this);
		findViewById(R.id.ln_remove_group).setOnClickListener(this);
		findViewById(R.id.ln_update_group).setOnClickListener(this);

		mSpContact.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> adap, View v, int pos,
					long arg3) {
				if (pos > 0 && lstContact != null && lstContact.size() > pos) {
					// TODO
					if (mGroupMemberAdapter != null
							&& mGroupMemberAdapter.getCount() > 9) {
						MessageManager.showToast(EditGroupActivity.this,
								"This group already have 10 members!");
					} else {
						Contact c = lstContact.get(pos);
						if (mWSGroup == null)
							mWSGroup = new GroupWSControl(
									EditGroupActivity.this,
									EditGroupActivity.this);
						mWSGroup.addGroupMember(Utility.getStringPreference(
								EditGroupActivity.this,
								Utility.KEY_LOGIN_TOKEN, ""), group.getID(), c
								.getID());
					}
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.ln_save_group) {
			this.finish();
		} else if (v.getId() == R.id.ln_remove_group) {
			if (mDeleteConfirmDialog != null) {
				mDeleteConfirmDialog.dismiss();
				mDeleteConfirmDialog = null;
			}
			mDeleteConfirmDialog = new DeleteConfirmDialog(getParent()) {
				@Override
				public void onConfirm() {
					if (mWSGroup == null)
						mWSGroup = new GroupWSControl(EditGroupActivity.this, EditGroupActivity.this);
					mWSGroup.deleteGroup(Utility.getStringPreference(EditGroupActivity.this,
							Utility.KEY_LOGIN_TOKEN, ""), group.getID() + "");
				}
			};
			mDeleteConfirmDialog.setTitle("Remove Group");
			mDeleteConfirmDialog
					.setMessage("Are you sure you wish to remove this group?");
			mDeleteConfirmDialog.show();

		} else if (v.getId() == R.id.ln_update_group) {
			String newGroupName = mEdtGroupName.getText().toString();
			if (newGroupName.length() > 0) {
				if (mWSGroup == null)
					mWSGroup = new GroupWSControl(this, this);
				mWSGroup.editGroup(Utility.getStringPreference(this,
						Utility.KEY_LOGIN_TOKEN, ""), group.getID(),
						newGroupName);
			}
		}
	}

	@Override
	protected void onDestroy() {
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
		if (mDeleteConfirmDialog != null) {
			mDeleteConfirmDialog.dismiss();
			mDeleteConfirmDialog = null;
		}
		if (mWSContact != null) {
			mWSContact.cancel();
			mWSContact = null;
		}
		if (mWSGroup != null) {
			mWSGroup.cancel();
			mWSGroup = null;
		}
		super.onDestroy();

	}

	@Override
	public void onConnectionOpen(WebServiceFlag flag) {
		if (flag == WebServiceFlag.GET_CONTACT) {
			if (lstContact != null && lstContact.size() > 1)
				return;
		}
		// else if (flag == WebServiceFlag.GET_GROUP_MEMBER) {
		// if (mGroupMemberAdapter != null
		// && mGroupMemberAdapter.getCount() > 0)
		// return;
		// }
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
		mDialog = new LoadingDialog(getParent());
		mDialog.setCancelable(false);
		mDialog.show();

	}

	@Override
	public void onConnectionError(WebServiceFlag flag, String error) {
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
		if (flag == WebServiceFlag.EDIT_GROUP_NAME) {
			mEdtGroupName.setText(group.getTitle());
		} else if (flag == WebServiceFlag.GET_GROUP_NAME) {
			getGroupMember();
		}
		MessageManager.showToast(this, error);

	}

	@Override
	public void onConnectionDone(WebServiceFlag flag, String response) {
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}

		if (flag == WebServiceFlag.EDIT_GROUP_NAME) {
			String returnValue = mWSGroup.parseAction(response,
					"UpdateGroupNameResult");
			if (returnValue != null && returnValue.length() > 0) {
				MessageManager.showToast(this, returnValue);
			}
		} else if (flag == WebServiceFlag.GET_CONTACT) {
			lstContact = mWSContact.parseContact(response);
			mTAContact.clear();
			for (int i = 0; i < lstContact.size(); i++) {
				mTAContact.add(lstContact.get(i), i);
			}
			Contact contact = new Contact();
			contact.setName("[Choose from Contacts]");
			lstContact.add(0, contact);
			ArrayAdapter<Contact> contactAdapter = new ArrayAdapter<Contact>(
					this, R.layout.spinner_item, lstContact);
			contactAdapter.setDropDownViewResource(R.layout.spinner_item);
			mSpContact.setAdapter(contactAdapter);

		} else if (flag == WebServiceFlag.GET_GROUP_MEMBER) {
			ArrayList<GroupMember> lst = mWSGroup.parseGroupMembers(response);
			mTAGroupMember.clear();
			for (int i = 0; i < lst.size(); i++) {
				mTAGroupMember.add(lst.get(i), group.getID(), i);
			}
			setGroupMemberAdapter(lst);

		} else if (flag == WebServiceFlag.DELETE_GROUP) {
			String returnValue = mWSGroup.parseAction(response,
					"DeleteGroupsFromListResult");
			if (returnValue != null && returnValue.length() > 0) {
				MessageManager.showToast(this, returnValue);
			}
			this.finish();

		} else if (flag == WebServiceFlag.DELETE_GROUP_MEMBER
				|| flag == WebServiceFlag.ADD_GROUP_MEMBER) {
			mSpContact.setSelection(0);
			if (mWSGroup == null)
				mWSGroup = new GroupWSControl(this, this);
			mWSGroup.getGroupMember(Utility.getStringPreference(this,
					Utility.KEY_LOGIN_TOKEN, ""), group.getID());

		} else if (flag == WebServiceFlag.GET_GROUP_NAME) {
			mEdtGroupName.setText(mWSGroup.parseAction(response,
					"GetGroupNameResult"));
			getGroupMember();
		}

	}

	private void getGroupMember() {
		// member
		setGroupMemberAdapter(mTAGroupMember.getItems(group.getID()));
		if (mWSGroup == null)
			mWSGroup = new GroupWSControl(this, this);
		mWSGroup.getGroupMember(
				Utility.getStringPreference(this, Utility.KEY_LOGIN_TOKEN, ""),
				group.getID());
	}
}